<?php

class Webmix_AlbumController extends Core_Controller_Action_Standard
{

  public function indexAction()
  {
    $this->view->someVar = 'someVal';
  }
  public function createAction()
  {
	if( !$this->_helper->requireUser()->isValid() ) {
		return;
	}
    
    //set type when create block
    if($this->_getParam('action_type')){
        $this->view->action_type = $action_type = $this->_getParam('action_type');
    }
    
    $this->view->webmix_id = $this->_getParam('webmix');;
    $this->view->admin = $this->_getParam('a',0);
    
    $this->view->form = $form = new Webmix_Form_Album_Create();
    
    // Check post
    if(!$this->getRequest()->isPost()){
        return;
    }
    
    
    if (!isset($_POST['key']) || empty($_POST["key"])){
           $form->addError('Your artist name not found.');
           return;
    }   
    
    $this->view->isValidF = true;
    // Check form validate
    if(!$form->isValid($this->getRequest()->getPost())){
        $this->view->isValidF = false; 
              
        return;
    }
    
    $this->view->viewer = $viewer = Engine_Api::_()->user()->getViewer();

    $values = $form->getValues();
   
    $photo_url = '';
    //refresh photo when upload a new one
    if($values['file_id']){
        $photo = Engine_Api::_()->getItemTable('storage_file')->getFile($values['file_id'],'thumb.normal');                            
        $photo_url = $photo->map();
        $this->view->photo_url = $photo_url;               
    }     
    
    //check if choose create new
    if($values['comp_id'] == 0){

        $table = Engine_Api::_()->getDbTable('musicalbums','webmix');
        
        //check existed company-country-link
        $check = $table->select()
               // ->where('country_id = ?',$values['country_id'])
                ->where('title = ?',$values['title'])
                ->where('link = ?',$values['link'])
                //Onwer not approved OR Approved of other users(admin)
                //->where('(owner_id = ? AND approve = 0) OR (approve = 1 AND owner_id <> ?)',$viewer->getIdentity())
                
                //not duplicate db when approve 
                ->where('owner_id = ? OR approve = 1 ',$viewer->getIdentity())
                ;
                
        $check_result = $table->fetchAll($check);
        if(count($check_result)>0){
            $form->addError('Your album has exist.');
            return;
        }
        
        //save form values
        $db = $table->getAdapter();
        $db->beginTransaction();
        try
        {            
            $company = $table->createRow();
            $company->setFromArray($values);
//            if($action_type == 'admin_create'){
//                $company->type = 'admin';
//                $company->approve = 1;
//            }
            $company->owner_id = $viewer->getIdentity();
            $company->photo_id = $values['file_id'];
            if (!empty($photo_url)) {
                $company->photo_url =  $photo_url;
            }
            $company->save();
            $db->commit();   
            $form->addNotice($this->view->translate('Your album created successfully.'));                  
            
            //Call hook to set country company_count
            $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('setCountryAlbumCount', array(
              'country_create' => $values['country_id'],
            ));
            
            // Notifications
            $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
            $userTable = Engine_Api::_()->getItemTable('user');
            $admin_id = $userTable->select()
                    ->where('level_id = 1')
                    ->query()
                    ->fetchColumn();
            $type = 'webmix_album_create';
            
            foreach( $userTable->find($admin_id) as $admin ) {
                $notifyApi->addNotification($admin, $viewer, $company, $type 
    //            ,array('message' => $this->view->BBCode($post->body),)
                );                        
            }       
        }
        catch(Exception $e)
        {
            $db->rollBack();
            throw $e;
        }        
    }
       
    
  }
  
  public function uploadAction(){
    if( !$this->_helper->requireUser()->isValid() ) {
    		return;
    	}
    $this->view->type = $type = $this->_getParam('type');
    $this->view->id = $this->_getParam('id');
    $this->view->form = $form = new Webmix_Form_Company_Upload();   
    
    // Check post form
    if( !$this->getRequest()->isPost() ) {
      return;
    }
    if( !$form->isValid($this->getRequest()->getPost()) ) {
      return;
    }

    $table = Engine_Api::_()->getDbTable('musicalbums','webmix'); 
         
  
    $uploadPhoto = $this->_getParam("uploadPhoto");
    
    $values = $form->getValues(); 
//    $this->_resizeImages($this->getForm()->Filedata->getFileName());
    $file_id = $table->setPhoto($form->Filedata);


    $type = 'thumb.normal';
    $file = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id, $type);
        if( !$file ) {
            return ;
        } 
    //get normal photo to save           
    $file_url = $file->map();
    $this->view->file_url = $file_url;
    $this->view->file_id = $file_id;
    
    //get full size photo to preview
    $preview = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id);
    $preview_url = $preview->map();
    $this->view->preview_url = $preview_url; 
    
  }
  
  
  public function previewAction(){
        
        $table = Engine_Api::_()->getDbTable('companies','webmix'); 
        $file_id = $table->setPhoto($_FILES['image']); 
        $type = 'thumb.normal';
        $file = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id, $type);
            if( !$file ) {
                return ;
            } 
        //get normal photo to save           
        $file_url = $file->map();
        $this->view->file_url = $file_url;
        $this->view->file_id = $file_id;
        
        //get full size photo to preview
        $preview = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id);
        $preview_url = $preview->map();
        $this->view->preview_url = $preview_url;                
  } 
  public function previewexAction(){
        if(!$this->getRequest()->isPost()) return;
        $table = Engine_Api::_()->getDbTable('musicalbums','webmix'); 
        $file_id = $table->setPhoto($_FILES['image']); 
        $type = 'thumb.normal';
        $file = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id, $type);
            if( !$file ) {
                return ;
            } 
        //get normal photo to save           
        $file_url = $file->map();
        $this->view->file_url = $file_url;
        $this->view->file_id = $file_id;
        
        //get full size photo to preview
        $preview = Engine_Api::_()->getItemTable('storage_file')->getFile($file_id);
        $preview_url = $preview->map();
        $this->view->preview_url = $preview_url;                
  }
    
    
  public function editAction(){
    	if( !$this->_helper->requireUser()->isValid() ) {
    		return;
    	}     
        
        //get company_id when edit in Admin
        $album_id = $this->view->id = $this->_getParam('id');
        //get photo_id when upload image in admin edit
        $photo_id = $this->_getParam('photo');
        
        $this->view->form = $form = new Webmix_Form_Album_Create();
        
        $photo_url = '';        
        if($album_id){
            $album = Engine_Api::_()->getItem('webmix_musicalbum',$album_id);    
            $form->populate($album->toArray());
            $this->view->id = $album_id;
            if (empty($photo_id)) $photo_id = $album->photo_id;
            if($photo_id){
                $photo = Engine_Api::_()->getItemTable('storage_file')->getFile($photo_id,'thumb.normal');                            
                $photo_url = $photo->map();
                $this->view->photo_url = $photo_url;           
            }
            else{
                $this->view->photo_url = $album->getPhotoUrl('thumb.normal');                        
            }               

            $this->view->action_type = $action_type = 'admin_edit';  
        }

            
        // Check post form
        if( !$this->getRequest()->isPost() ) {
          return;
        }
        
        if( !$form->isValid($this->getRequest()->getPost()) ) {
          return;
        }
        
        $values = $form->getValues();    
        if(!$album){
            $album = Engine_Api::_()->getItem('webmix_musicalbum',$values['comp_id']);                
        }  
        
        if(!$album) {
            $form->addNotice('your album music not found.');
            return;
        }
        
        $table = Engine_Api::_()->getDbtable('musicalbums','webmix');
        $check = $table->select()
            ->where('`key` = ?',$values['key'])
            ->where('musicalbum_id <> ?',$values['comp_id']);
           
        $check_result = $table->fetchAll($check);
        if(count($check_result) > 0) {
            $form->addError('Your album key had existed.');
            return;
        } 
        
        //refresh photo when upload a new one
        if(!empty($values['file_id'])){
            $photo = Engine_Api::_()->getItemTable('storage_file')->getFile($values['file_id'],'thumb.normal');                            
            $photo_url = $photo->map();
            $this->view->photo_url = $photo_url;               
        }

                      
        // Process
        $db = Engine_Db_Table::getDefaultAdapter();
        $db->beginTransaction();        
        
        try{
            $album->setFromArray($values);
            if(!empty($values['file_id'])){
                $album->photo_id = $values['file_id'];                
            }
            elseif(!empty($photo_id)){
                $album->photo_id = $photo_id;    
            }
            if (!empty($photo_url)) {
                $album->photo_url =  $photo_url;
            }
            
            $album->save();
            $db->commit();   
            
           
             
                        
            $form->addNotice($this->view->translate('Your changes have been saved.'));
            if($action_type){
                return $this->_forward('success', 'utility', 'core', array(
                'smoothboxClose' => 1000,
                'parentRefresh' => 10,
                'format'=> 'smoothbox',
                'messages' => array('Your changes have been saved.')
                ));
            }
        }
        catch(Exception $e)
        {
            $db->rollback();
            throw $e;
        }
    }
    
  public function deleteAction()
  {
    if( !$this->_helper->requireUser()->isValid() ) {
  		return;
 	}     
    $id = $this->_getParam('id', null);
    $album = Engine_Api::_()->getItem('webmix_musicalbum', $id);
    $this->view->form = $form = new Webmix_Form_Company_Delete();
    $form->setDescription('Delete webmix album');
    // deleting user
    //$form->user_id->setValue($id);

    if( $this->getRequest()->isPost() ) {
      $db = Engine_Api::_()->getDbtable('musicalbums', 'webmix')->getAdapter();
      $db->beginTransaction();

      try {
        //Call hook to delete block
        $event = Engine_Hooks_Dispatcher::getInstance()->callEvent('deleteAlbum', array(
          'company' => $album->musicalbum_id,
        ));       
                
        $album->delete();        
        $db->commit();
        

      } catch( Exception $e ) {
        $db->rollBack();
        throw $e;
      }
      
      return $this->_forward('success', 'utility', 'core', array(
        'smoothboxClose' => true,
        'parentRefresh' => true,
        'format'=> 'smoothbox',
        'messages' => array('This album has been successfully deleted.')
      ));
    }
  }

    public function requestAction(){
        if( !$this->_helper->requireUser()->isValid() ) {
      		return;
     	}           
        $this->view->form = $form = new Webmix_Form_Company_Request();
        $viewer = Engine_Api::_()->user()->getViewer();  
              
       if( !$this->getRequest()->isPost() ) {
            return;
       }
       
       // Check form validate
        if(!$form->isValid($this->getRequest()->getPost())){
            return;
        }
        
        $values = $form->getValues();    
        
        //get country
        if(isset($values['country'])){
            $country = Engine_Api::_()->getItem('webmix_country',$values['country']);            
        }      
         
        // Mail gets logged into database, so perform try/catch in this Controller
        $db = Engine_Db_Table::getDefaultAdapter();
        $db->beginTransaction();
        try {
              // the contact form is emailed to the first SuperAdmin by default
        	  $users_table = Engine_Api::_()->getDbtable('users', 'user');
        	  $users_select = $users_table->select()
        	  		->where('level_id = ?', 1)
        	  		->where('enabled >= ?', 1);
        	  $super_admin = $users_table->fetchRow($users_select);
              $adminEmail = Engine_Api::_()->getApi('settings', 'core')->getSetting('core.mail.contact');
              if( !$adminEmail ) {
                $adminEmail = $super_admin->email;
              }
        
              // Make params
              $mail_settings = array(
                'host' => $_SERVER['HTTP_HOST'],
                'email' => $adminEmail,
                'date' => time(),
                'recipient_title' => $super_admin->getTitle(),
                'recipient_link' => $super_admin->getHref(),
                'recipient_photo' => $super_admin->getPhotoUrl('thumb.icon'),
                'sender_title' => $viewer->getTitle(),
                'object_title' => $country->title,
                'sender_email' => $viewer->email,
                'message' => $values['message'],
              );
        
              if( $viewer && $viewer->getIdentity() ) {
                $mail_settings['sender_title'] .= ' (' . $viewer->email . ')';
              }
              // send email
              Engine_Api::_()->getApi('mail', 'core')->sendSystemRaw(
                $adminEmail,
                'notify_webmix_company_request',
                $mail_settings
              );
              
              // if the above did not throw an exception, it succeeded
              $db->commit();
        } catch( Zend_Mail_Transport_Exception $e ) {
              $db->rollBack();
              throw $e;
        }


        // Notifications
        $notifyApi = Engine_Api::_()->getDbtable('notifications', 'activity');
        
        //get list admin
        $userTable = Engine_Api::_()->getItemTable('user');
        $admin_id = $userTable->select()
                ->where('level_id = 1')
                ->query()
                ->fetchColumn();
        $type = 'webmix_company_request';
                
        // do notification
        foreach( $userTable->find($admin_id) as $admin ) {
            $notifyApi->addNotification($admin, $viewer, $country, $type 
            );                        
        }
            
        $this->_forward('success', 'utility', 'core', array(
    				'format'=> 'smoothbox',
    				'messages' => array(Zend_Registry::get('Zend_Translate')->_("Your request has been submmitted to admin. You'll will get the response soon. Thank you.")),
    				'smoothboxClose' => 2000,
    				'parentRefresh' => false,
        ));        
    }
}

